/*
 * Created by guoyh on Sun Dec 11 2022 17:40:19
 * leetcode NO.2, https://leetcode.cn/problems/add-two-numbers/ 
 * 
 * 输入：l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
 * 输出：[8,9,9,9,0,0,0,1]
 * 
 */
#include <iostream>
// #include<vector>
#include <gtest/gtest.h>

using namespace std;
struct ListNode {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* dummy = new ListNode();
        ListNode* tail = dummy;
        // 进位
        int flag = 0;
        while(l1 || l2 || flag){
            int sum = 0;
            int val = 0;
            if(l1 != nullptr){
                // cout<<"l1->val:"<<l1->val<<","<<endl;

                sum += l1->val;
                l1 = l1->next;
            }
            if(l2 != nullptr){
                // cout<<"l2->val:"<<l2->val<<","<<endl;
                sum+= l2->val;
                l2 = l2->next;
            }
            sum+=flag;
            if(sum > 9){
                flag = 1;
                val = sum - 10;
            }else{
                flag = 0;
                val = sum;
            }
            ListNode* newNode = new ListNode(val);
            newNode->next = nullptr;
            tail->next = newNode;
            tail = tail->next;
        }
        
        return dummy->next;
    }
};

// 尾插法创建链表
ListNode* build_linklist(vector<int> v){
    ListNode* dummy = new ListNode();
    ListNode* tail = dummy;
    for(int i : v){
        ListNode* newNode = new ListNode(i);
        newNode->next = nullptr;
        tail->next = newNode;
        tail = tail->next;
    }
    return dummy->next;
}


void print(ListNode* l){
    while(l){
        cout<<l->val<<",";
        l = l->next;
    }
    cout<<endl;
}

int add(int a, int b) {
    return a + b;
}

TEST(MyTest, AddTest) {
    vector<int> v1 = {9,9,9,9,9,9,9,9,9};
    vector<int> v2 = {9,9,9,9};
    ListNode* l1 = build_linklist(v1);
    ListNode* l2 = build_linklist(v2);
    Solution slu;
    ListNode* res = slu.addTwoNumbers(l1, l2);
    print(res);
    EXPECT_NE(res, nullptr);
}

int main(int argc, char *argv[]) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
